package com.pine.sunshineelder.common.web.spring;

import java.util.List;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.pine.sunshineelder.common.dto.JSONResponse;
import com.pine.sunshineelder.common.exception.ThisSystemException;

@RestControllerAdvice
public class ThisSystemExceptionHandler {
	@ExceptionHandler
	public JSONResponse handleThisSystemException(ThisSystemException e) {
		return JSONResponse.fail(e.getCode(), e.getMessage());
	}

	@ExceptionHandler
	public JSONResponse handleValidationError(BindException e) {

		List<ObjectError> allErrors = e.getAllErrors();
		StringBuilder message = new StringBuilder();
		for (ObjectError objectError : allErrors) {
			if (objectError instanceof FieldError) {
				FieldError fe = (FieldError) objectError;
				message.append(fe.getField());
			}
			message.append(objectError.getDefaultMessage());
		}
		return JSONResponse.fail("param-error", message.toString());

	}

	@ExceptionHandler
	public JSONResponse handleThrowable(Throwable e) {
		e.printStackTrace();
		return JSONResponse.fail("系统好忙");
	}

}
